package edu.luc.cs.trull.demo.wristwatch;

import java.awt.Toolkit;
import java.beans.PropertyChangeEvent;

import edu.luc.cs.trull.EmitComponent;

/**
 * update =
 *   loop
 *     TICK -> { time ++; } emit UPDATE
 */

public class Update extends EmitComponent implements EventLabels {

	private DateModel data;
	private AlarmModel alarm;
	
	private int snoozeTicks = 120;
		
	public Update(DateModel data) {
		this.data = data;
	}
	
	public Update(DateModel data, AlarmModel alarm) {
		this.data = data;
		this.alarm = alarm;
	}
	
	public void alarm() {
		alarm.setAlarming(true);
		alarm.setSnoozing( false );
		snoozeTicks = 120;
		scheduleEvent(SOUND_ON);
	}
	
    public void propertyChange(final PropertyChangeEvent event) {
    		  	
	  	if (TICK.equals(event.getPropertyName())) {
			data.incrementSecond();
			if(!alarm.isAlarming()){
		  		if(data.getTime() == alarm.getAlarmTime1() 
						|| data.getTime() == alarm.getAlarmTime2()
						|| data.getTime() == alarm.getAlarmTime3())	{
					this.alarm();
				}
		  	}
			if(alarm.isAlarming()) 
				Toolkit.getDefaultToolkit() .beep() ;
			scheduleEvent(UPDATE);
		}
	  	
	  	// If light button is pressed briefly 
	  	// then stop and snoooze the alarm .
	  	if (SNOOZE.equals( event.getPropertyName())) {
	  		alarm.setAlarming( false );
	  		alarm.setSnoozing( true );
	  	}
	  	// If light button is pressed for more than one second
	  	// Reset all the values & stop the alarm
	  	else if(SOUND_OFF.equals( event.getPropertyName())){
	  		alarm.setAlarming( false );
	  		alarm.setSnoozing( false );
	  		snoozeTicks = 120;
	  	}
	  	
	  	// If the alarm is snoozing, count the ticks
	  	// If 120 ticks are done, start the alarm again
	  	if(alarm.isSnoozing()) 	{
	  		snoozeTicks --;
	  		if(snoozeTicks == 0) {
	  			this.alarm();
	  		}	
	  	}
	  	
	}
}
